/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.appspot.trick.it.admin.task;

import com.appspot.trick.it.admin.api.DriveAPIService;
import com.appspot.trick.it.admin.api.GaeArticleAPIService;
import com.appspot.trick.it.admin.controller.MainController;
import com.appspot.trick.it.admin.model.ArticleModel;
import com.google.api.services.drive.model.File;
import javafx.concurrent.Service;
import javafx.concurrent.Task;


/**
 *
 * @author takahara
 */
public class ArticleAddTask extends Service<ArticleModel> {
    
    private ArticleModel parentModel;

    public void run(ArticleModel parentModel) throws Exception {
        this.parentModel = parentModel;
        this.restart();
    }

    @Override
    protected Task<ArticleModel> createTask() {
        return new Task<ArticleModel>() {

            @Override
            protected ArticleModel call() throws Exception {
                
                DriveAPIService driveService = new DriveAPIService();
                String googleDriveKey = MainController.getInstance().getSiteMstEntity().googleDriveKey;
                
                
                ArticleModel model = new ArticleModel();
                model.setTitle("新しい記事");
                
                // 新規登録
                GaeArticleAPIService gaeService = new GaeArticleAPIService(MainController.getInstance().getSiteMstEntity());
                ArticleModel newModel = gaeService.add(parentModel.getKey(), model);
                
                // Google Drive に商品ディレクトリを作成(未作成の場合)
                File folder;
                if (parentModel.getKey() == null) {
                    folder = driveService.insertFolder(googleDriveKey, newModel.getKey());
                }else {
                    folder = driveService.insertFolder(parentModel.getDriveDriKey(), newModel.getKey());
                }
                
                // Google Drive Dri のキーをGAEに登録
                newModel.setDriveDriKey(folder.getId());
                gaeService.update(newModel);
                
                return newModel;
            }
        };

    }

}
